package com.weiyi.weiman.quartz;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.weiyi.weiman.domain.Const.ComicsConst;
import com.weiyi.weiman.domain.Const.ComicsRankConst;
import com.weiyi.weiman.utils.RedisUtils;
import comics.Comics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;

/**
 * @Author zhang
 * @Date 2021/5/27 下午2:13
 * @Description 统计信息的定时任务
 * @Version 1.0
 **/
@Component
@Slf4j
public class StaticsTask {

    @Autowired
    private RedisUtils redisUtils;

    private final String COMICS_INDEX_LOG_PATH = "comicsIndexStatics";

    /**
     * 定时更新热门搜索列表
     * @throws Exception
     */
    @Scheduled(cron = " 0 30 */5 * * ?")
    private void updateHotSearch() throws Exception {
        File path = new File(COMICS_INDEX_LOG_PATH);
        File[] logFile = path.listFiles();
        //根据创建时间对文件进行降序排序
        Arrays.sort(logFile, new Comparator<File>() {
            @Override
            public int compare(File file1, File file2) {
                return (int)(file2.lastModified()-file1.lastModified());
            }
        });
        if (logFile.length >= 1) {
            redisUtils.delete(ComicsRankConst.COMICS_HOT_SEARCH);
            BufferedReader reader = new BufferedReader(new FileReader(logFile[0]));
            String comicsIndexString = null;
            // 读取文件中所有漫画信息
            while (!StringUtils.isEmpty(comicsIndexString = reader.readLine())) {
                String[] index = comicsIndexString.split(",");
                redisUtils.zAdd(ComicsRankConst.COMICS_HOT_SEARCH, index[0], Double.parseDouble(index[4]));
            }
            reader.close();
            log.info("热门搜索列表更新完成");
        }
    }
}
